package pers.vinsonws.jianghu.serverspring.controller;

import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pers.vinsonws.jianghu.codeCompont.MsgEveryPro;
import pers.vinsonws.jianghu.serverspring.channel.ChannelManager;
import pers.vinsonws.jianghu.serverspring.service.ChatRoomServiceImpl;
import pers.vinsonws.jianghu.serverspring.service.UserServiceImpl;
import pers.vinsonws.jianghu.serverspring.session.NetSession;
import pers.vinsonws.jianghu.serverspring.session.SessionManager;
import pers.vinsonws.jianghu.tools.MergeMessage;
import pers.vinsonws.jianghu.util.MessageLabel;
import pers.vinsonws.jianghu.util.User;

import java.util.*;

/**
 * @auther vinsonws
 * @date 2018/11/6 0:14
 * 聊天信息的接收处理与发送处理
 * 这里写聊天，聊天要满足一下几个要求
 *                  1、要有一个管理session的组件
 *                  2、信息的处理与选择发送
 * 目前从外面直接传入session
 *
 * 我后面试着能否改变这里的实现方法，将不由ctrl控制发送
 * 我决定这里的入口是一个MsgEveryPro.Message，出口也是一个MsgEveryPro.Message
 * 下面行注释部分移到上层
 */
@Component
public class ChatCtrl {
    private static final Logger log = LoggerFactory.getLogger(ChatCtrl.class);
    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private ChatRoomServiceImpl chatRoomService;

    @Autowired
    private ChannelManager channelManager;

    public void dealChatOneMessage(MsgEveryPro.Message message){
        if (message.getType() != 7){
            throw new IllegalStateException("一对一聊天不合法类型");
        }
        Channel channelSend= channelManager.getChannelByUserId(message.getUserSendId());
        Channel channelRecv = channelManager.getChannelByUserId(message.getChatRoomOrUserRecvId());
        if (channelRecv == null){
            //用户未上线
            MsgEveryPro.Message.Builder message1 = MsgEveryPro.Message.newBuilder();
            message1.setType(7);
            message1.setDateLong(System.currentTimeMillis());
            message1.setChatRoomOrUserRecvId(message.getUserSendId());
            message1.setUserSendId(message.getChatRoomOrUserRecvId());
            message1.setOnline(true);
            String[] ss = {userService.getUserById(message.getChatRoomOrUserRecvId()).getUserName(),"用户不在线"};
            message1.setMessage(MergeMessage.infoToMessage(ss, message.getType()));
            channelSend.writeAndFlush(message1.build());
            return;
        }
        channelRecv.writeAndFlush(message);
    }

    public void dealChatRoomMessage(MsgEveryPro.Message message){
        if (message.getType() != 8){
            throw new IllegalStateException("聊天室不合法类型");
        }
        //首先把该聊天室用户的id全部理出
        Set<User> userSet = chatRoomService.getAllUserByChatRoomId(message.getChatRoomOrUserRecvId());
        Set<Integer> userIdSetOnline = new HashSet<>();
        for (Iterator<User> it = userSet.iterator(); it.hasNext(); ) {
            User user = it.next();
            userIdSetOnline.add(user.getId());
        }
        //写消息message
//        MsgEveryPro.Message.Builder message1 = MsgEveryPro.Message.newBuilder();
//        message1.setType(8);
//        message1.setDateLong(System.currentTimeMillis());
//        message1.setUserSendId(message.getUserSendId());
//        message1.setChatRoomOrUserRecvId(message.getChatRoomOrUserRecvId());
//        message1.setMessage(message.getMessage());
//        message1.setOnline(true);
        //将该聊天室在线的用户列出//发送消息
        for (Iterator<Integer> it = userIdSetOnline.iterator(); it.hasNext(); ) {
            Integer userId = it.next();
            Channel channel = channelManager.getChannelByUserId(userId);
            if (channel == null) continue;
            NetSession recvSession = SessionManager.getSession(channel);
            recvSession.getChannel().writeAndFlush(message);
        }
    }
}
